package app.tasks.search;

import app.env.Data;
import app.agent.SearchAgent;
import app.env.Position;
import app.util.AppUtils;
import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

/**
 * @Name: WaitMessage
 * @Description:
 * @Author: colfish
 * @Date: 2021/4/23
 */
public class WaitMessage extends OneShotBehaviour {

    private static final long serialVersionUID = -4500121901459229967L;

    private SearchAgent searchAgent;

    int nextState;

    public WaitMessage(SearchAgent searchAgent){
        this.searchAgent = searchAgent;
        nextState = 1;
    }

    @Override
    public void action() {
        nextState = 1;
        ACLMessage signalReceived = searchAgent.receive();
        if(signalReceived!=null) {
            AID sender = signalReceived.getSender();
            String[] content = signalReceived.getContent().split(";");
            String message = content[0];
            // Move
            // TODO 移动后保存轨迹
            if(message.equals(Data.SEARCH_MOVE_RANDOM)){
                // 得到要移动到的目标点
                Position tarPos = AppUtils.getRandomPosition(searchAgent.position, 5, searchAgent.range);
                // 得到要移动的目的地坐标
                Position retPos = AppUtils.moveAgent1(searchAgent.getLocalName(), searchAgent.position, tarPos);
                searchAgent.position.x = retPos.x;
                searchAgent.position.y = retPos.y;
                nextState = 2;
            }else if(message.equals(Data.SEARCH_MOVE_MAX)){
                Position tarPos = AppUtils.getMaxPos(searchAgent.position, searchAgent.range);
                AppUtils.moveAgent2(searchAgent.getLocalName(), searchAgent.position, tarPos,1 );
                searchAgent.position.x = tarPos.x;
                searchAgent.position.y = tarPos.y;
                nextState = 2;
            }else if(message.equals(Data.SEARCH_MOVE_TARGET)){
                String[] coordinate = content[1].split(",");
                Position tarPos = new Position(coordinate[0], coordinate[1]);
                AppUtils.moveAgent2(searchAgent.getLocalName(), searchAgent.position, tarPos, 0);
                searchAgent.position.x = tarPos.x;
                searchAgent.position.y = tarPos.y;
                nextState = 0;
            }else if(message.equals(Data.SEARCH_AGAIN)){
                nextState = 2;
            }else if(message.equals(Data.SEARCH_STOP)){
                nextState = 0;
            }
        }
    }

    @Override
    public int onEnd() {
        return nextState;
    }
}
